from datetime import datetime
from src.common.config import config
from src.common.logger import getLogger
from src.agentic.agent.AgentTools import AgentTools
from src.agentic.config.GraphStore import GraphStore
from src.agentic.config.VectorStore import VectorStore
from src.agentic.rag.program.ProgramRAG import ProgramRAG
from src.agentic.config.LanguageModel import LanguageModel
from src.agentic.config.EmbeddingModel import EmbeddingModel
from src.modules.memory.service import HistoryRecordService, MemoryDetailService

logger = getLogger()

def invoke_retrieval_program(form):
    start_time = datetime.now().second

    HistoryRecordService.insert_history_memory(form)

    base_url = "http://localhost:11434"
    llm = LanguageModel("qwen3:4b", base_url, None).new_llm_model()

    embedding = EmbeddingModel("bge-m3", base_url).new_embed_model()

    config_dict = config.parse_config_key(["qdrant"])
    collection_prefix = config_dict.get("collection_prefix", "")
    logger.info(f"invoke_retrieval_program collection_prefix: {collection_prefix}")

    vector_store = VectorStore()

    graph_store = GraphStore().new_graph_store()

    tools = AgentTools().get_execute_tools()

    rag_retriever = ProgramRAG(llm, embedding, tools, 5)
    retrieve_result = rag_retriever.invoke(form.get("query"), form.get("pattern"))

    MemoryDetailService.insert_memory_detail_ai(form, retrieve_result)

    logger.info(f"invoke_retrieval_program time: {datetime.now().second - start_time} s")
    return retrieve_result
